// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import PipeGroup from "./pipe_group";
import store from "./common";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PipeGroupManager extends cc.Component {

    @property(cc.Prefab)
    pipePrefab: cc.Prefab = null;

    @property(cc.Node)
    pipeLayer: cc.Node = null;

    @property
    initPipeX: number = 0;

    @property
    spawnInterval: number = 0;

    private pipePool: cc.NodePool = null;

    onLoad() {
        store.pipeManager = this;
        this.pipePool = new cc.NodePool();
    }

    startSpawn() {
        this.spawnPipe();
        this.schedule(this.spawnPipe, this.spawnInterval);
    }

    spawnPipe() {
        let pipeGroup = null;
        if (this.pipePool.size() > 0) {
            console.log('复用管道节点');
            pipeGroup = this.pipePool.get();
        } else {
            pipeGroup = cc.instantiate(this.pipePrefab);
            console.log('创建新的管道节点');
        }

        this.pipeLayer.addChild(pipeGroup);
        pipeGroup.active = true;
        pipeGroup.x = this.initPipeX;
    }

    recyclePipe(pipe) {
        pipe.active = false;
        this.pipePool.put(pipe);
    }

    reset() {
        this.unschedule(this.spawnPipe);
        this.pipePool.clear();
    }
}
